package org.haredot.service.impl;

import org.haredot.dto.Permission;
import org.haredot.dto.UserDetailsDTO;
import org.haredot.entity.Role;
import org.haredot.mapper.UserDetailsMapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserDetailsMapper userDetailsMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDetailsDTO userDetails = userDetailsMapper.findUserByUsername(username);

        if (userDetails == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }

        List<Role> roles = userDetails.getRoles();

        if (roles.isEmpty()) {
            throw new RuntimeException("未绑定角色");
        }
        // 判断 角色中是否 包含 超级管理员
        long count = roles.stream().filter(role -> "super-admin".equals(role.getRemark())).count();

        List<Permission> permissions = null;
        if (count > 0) {
            // 查询 网站的所有资源、作为 当前用户的权限
            permissions = userDetailsMapper.findAllResources();
        } else {
            // 根据 用户的角色 ，查询 该角色拥有的所有权限
            permissions = userDetailsMapper.findResourcesByRoleIds(roles);
        }

        if (permissions.isEmpty()) {
            throw new RuntimeException("权限不足");
        }

        userDetails.setAuthorities(permissions);

        return userDetails;
    }
}
